import React, { useEffect, useState } from 'react'
import DetailContainer from '@/components/DetailContainer'
import Descriptions from '@/components/Descriptions'
import { Button, Col, Form, Input, InputNumber, message, Modal, Row, Select, Space, Table, Tag, Typography } from 'antd'
import { EditFormInline } from '@/components/CustomForm'
import { useForm } from 'antd/es/form/Form'
import { useFormAdd } from './useForm'
import useSearchWarehouse from '@/hooks/useSearchWarehouse'
import useSearchUser from '@/hooks/useSearchUser'
import { useAppSelector } from '@/store/hooks'
import { getProductClassConfigByType } from '@/api/goods'
import useSearchSupplierCooperate from '@/hooks/useSearchSupplierCooperate'
import './components/FormShare.less'
import { ImportOutlined, PlusOutlined, SearchOutlined } from '@ant-design/icons'
import { ProductSimpleVO } from './types'
import {
  createPurchaseOrder,
  createPurchaseOrderImportCommodity,
  getProductBySkuCode,
  getProductBySpuCode,
} from '@/api/purchase'
import dayjs from 'dayjs'
import * as mathjs from 'mathjs'
import { useNavigate } from 'react-router-dom'
import ImportFileModal from '@/components/ImportFileModal'
import { IMPORT_FILE_ENUM } from '@/constant'
import { useDetailedColumns, useViewSpuColumns } from './columns'
const Index: React.FC = () => {
  const grid = { xs: 24, sm: 24, md: 12, lg: 8, xl: 6, xxl: 6 }
  const [FormOrder] = useForm()
  const [formOrderSearch] = useForm()
  const [formSpuSearch] = useForm()
  const [FormUpload] = useForm()
  const navigate = useNavigate()
  const [ispedding, setispedding] = useState<boolean>(false)
  const [isModalShow, setisModalShow] = useState<boolean>(false)
  const { WareHouseOptions, handleSearchWareHouse } = useSearchWarehouse()
  const { UserOptions, handleSearchUser } = useSearchUser()
  const DICTDATA = useAppSelector((state) => state.login.DICTDATA)
  const { SupplierOption, handleSearchSupplier } = useSearchSupplierCooperate('supplierId')
  const [tableData, settableData] = useState<ProductSimpleVO[]>([])
  //大类
  const [classBig, setclassBig] = useState<IOptionItem[]>([])
  const [firstClassConfigName, setfirstClassConfigName] = useState('')
  const firstClassConfigId = Form.useWatch('firstClassConfigId', FormOrder)
  const productSeasonCode = Form.useWatch('productSeasonCode', FormOrder)
  const year = Form.useWatch('year', FormOrder)
  const purchaseType = Form.useWatch('purchaseType', FormOrder)
  const [viewList, setviewList] = useState<ProductSimpleVO[]>([])
  const [selectedRowKeys, setselectedRowKeys] = useState<React.Key[]>([])
  const [SkuOptions, setSkuOptions] = useState<IOptionItem[]>([])
  const [importFileShow, setimportFileShow] = useState(false)
  const [uploadLoading, setuploadLoading] = useState(false)
  useEffect(() => {
    getProductClassConfig()
    handleSearchWareHouse()
  }, [])
  useEffect(() => {
    settableData([])
  }, [firstClassConfigId, productSeasonCode, year, purchaseType])
  useEffect(() => {
    if (WareHouseOptions.length === 1) {
      FormOrder.setFieldValue('warehouse', WareHouseOptions[0].value)
    }
  }, [WareHouseOptions])
  const getProductClassConfig = async (type: 1 | 2 | 3 | 4 = 1) => {
    const res = await getProductClassConfigByType<{
      className: string
      classConfigId: string | number
    }>({ type, auth: 1 })
    const classIdOptions =
      res?.data?.map((item) => {
        return {
          label: item.className,
          value: item.classConfigId,
          isLeaf: false,
        }
      }) || []
    setclassBig(classIdOptions)
  }
  const handleAddInfo = async () => {
    if (!formOrderSearch.getFieldValue('skuCode')?.toString()) {
      message.warning('SKU商品不能为空')
      return
    }
    const res = await getProductBySkuCode({
      firstClassConfigId,
      year: year && dayjs(year).format('YYYY'),
      productSeasonCode,
      purchaseType,
      skuCode: formOrderSearch.getFieldValue('skuCode')?.toString(),
    })
    if (res.code === 200) {
      if (res.data == null) {
        message.warning('SKU商品不存在')
        return
      }
      const hasSku = tableData?.filter((item) => item?.skuCode == res?.data?.skuCode)
      if (hasSku.length > 0) {
        message.warning('已存在相同SKU商品')
        return
      }
      const data = {
        ...res?.data,
        commoditySize: res?.data?.size,
        ...formOrderSearch.getFieldsValue(),
        directSaleQty: formOrderSearch.getFieldValue('directSaleQty')
          ? formOrderSearch.getFieldValue('directSaleQty')
          : 0,
        franchisingQty: formOrderSearch.getFieldValue('franchisingQty')
          ? formOrderSearch.getFieldValue('franchisingQty')
          : 0,
        onlineQty: formOrderSearch.getFieldValue('onlineQty') ? formOrderSearch.getFieldValue('onlineQty') : 0,
      }
      settableData([...tableData, data])
      message.success('添加成功')
      formOrderSearch.setFieldValue('skuCode', null)
    }
  }
  const createOrder = async () => {
    await FormOrder.validateFields()
    if (tableData.length === 0) {
      message.warning('请添加SKU商品')
      return
    }
    const hasInputorderQty = tableData.every((item) => item.orderQty >= 0)
    if (!hasInputorderQty) {
      message.warning('请输入下单数量')
      return
    }
    const hasInputPurchasePrice = tableData.every((item) => item.purchasePrice >= 0)
    if (!hasInputPurchasePrice) {
      message.warning('请输入采购价格')
      return
    }
    const postParams = {
      ...FormOrder.getFieldsValue(),
      firstClassConfigName,
      year: FormOrder.getFieldValue('year') && dayjs(FormOrder.getFieldValue('year')).format('YYYY'),
      planDate: FormOrder.getFieldValue('planDate') && dayjs(FormOrder.getFieldValue('planDate')).format('YYYY-MM-DD'),
      requiredArrivalTime:
        FormOrder.getFieldValue('requiredArrivalTime') &&
        dayjs(FormOrder.getFieldValue('requiredArrivalTime')).format('YYYY-MM-DD'),
      trackOrderPersonWorkId: FormOrder.getFieldValue('trackOrderPersonWorkId')?.value,
      trackOrderPerson: FormOrder.getFieldValue('trackOrderPersonWorkId')?.label?.split('-')[1],
      purchaseOrderCommodityList: tableData?.map((item) => {
        const { size, ...items } = item
        return {
          ...items,
          skuCode: item?.skuCode?.toString(),
        }
      }),
    }
    const res = await createPurchaseOrder(postParams)
    if (res.code === 200) {
      message.open({
        type: 'success',
        content: (
          <Typography.Text>
            新建采购订单成功，订单号：
            <Typography.Link onClick={() => navigate('/purchase/order/detail?id=' + res?.data?.id)}>
              {res?.data?.purchaseOrderCode}
            </Typography.Link>
          </Typography.Text>
        ),
        duration: 5,
      })
      navigate('/purchase/order/list')
    }
  }
  const onModalCancel = () => {
    setisModalShow(false)
    setviewList([])
    formSpuSearch.resetFields()
    setselectedRowKeys([])
  }
  const handleAddSpu = async () => {
    if (!formSpuSearch.getFieldValue('spuCode')) {
      message.warning('SPU商品不能为空')
      return
    }
    const res = await getProductBySpuCode({
      firstClassConfigId,
      year: year && dayjs(year).format('YYYY'),
      productSeasonCode,
      purchaseType,
      spuCode: formSpuSearch.getFieldValue('spuCode'),
    })
    if (res.code === 200 && res?.data?.length > 0) {
      const datalist =
        res?.data?.map((item: any) => {
          return {
            ...item,
            commoditySize: item?.size,
          }
        }) || []
      setviewList(datalist)
      message.success('查询成功')
    }
  }
  const addTotableData = () => {
    const selectedRowInfos = viewList?.filter((item) => selectedRowKeys?.includes(item?.skuCode))
    console.log(selectedRowInfos, viewList, 'selectedRowInfos')
    if (selectedRowInfos.length === 0) {
      message.warning('请添加SPU商品')
      return
    }
    const hasInputorderQty = selectedRowInfos.every((item) => item.orderQty >= 0)
    if (!hasInputorderQty) {
      message.warning('请输入下单数量')
      return
    }
    const hasInputPurchasePrice = selectedRowInfos.every((item) => item.purchasePrice >= 0)
    if (!hasInputPurchasePrice) {
      message.warning('请输入采购价格')
      return
    }
    const handleData =
      selectedRowInfos?.map((item: any) => {
        return {
          ...item,
          directSaleQty: item?.directSaleQty ? item.directSaleQty : 0,
          franchisingQty: item?.franchisingQty ? item.franchisingQty : 0,
          onlineQty: item?.onlineQty ? item.onlineQty : 0,
        }
      }) || []
    settableData([...tableData, ...handleData])
    onModalCancel()
  }
  const onSelectChange = (keys: React.Key[]) => {
    setselectedRowKeys(keys)
  }
  const importFileCancel = () => {
    setimportFileShow(false)
    FormUpload.resetFields()
  }
  const importFileOk = async () => {
    await FormUpload.validateFields()
    setuploadLoading(true)
    const data = new FormData()
    data.append('firstClassConfigId', firstClassConfigId)
    data.append('year', year && dayjs(year).format('YYYY'))
    data.append('productSeasonCode', productSeasonCode)
    data.append('purchaseType', purchaseType)
    data.append('file', FormUpload.getFieldValue('file'))
    const res = await createPurchaseOrderImportCommodity(data).finally(() => {
      setuploadLoading(false)
      FormUpload.resetFields()
    })
    if (res.code === 200) {
      importFileCancel()
      const list =
        res?.data
          ?.filter((item: any) => !tableData.some((table) => table?.skuCode == item?.skuCode))
          ?.map((item: any) => {
            return {
              ...item,
              originSalePrice: item?.tagPrice,
              spuName: item?.productName,
              designCode: item?.memoryCode,
              className: item?.wholeClassName,
              size: item?.commoditySize,
              directSaleQty: item?.directSaleQty ? item.directSaleQty : 0,
              franchisingQty: item?.franchisingQty ? item.franchisingQty : 0,
              onlineQty: item?.onlineQty ? item.onlineQty : 0,
            }
          }) || []
      settableData([...tableData, ...list])
    }
  }
  return (
    <DetailContainer
      className="purchase_order_add_page"
      footer={
        <Space>
          <Button type="primary" onClick={() => createOrder()} loading={ispedding}>
            创建采购单
          </Button>
        </Space>
      }
    >
      <Descriptions title="基础信息" list={[]}>
        <EditFormInline
          className="sep_forminline_style"
          editConfig={useFormAdd({
            WareHouseOptions,
            handleSearchWareHouse,
            UserOptions,
            handleSearchUser,
            DICTDATA,
            classBig,
            SupplierOption,
            handleSearchSupplier,
            setfirstClassConfigName,
          })}
          form={FormOrder}
          initialValues={{ planDate: dayjs(), requiredArrivalTime: dayjs(), year: dayjs() }}
        />
      </Descriptions>
      <Descriptions title="订单留言" list={[]} column={{ xxl: 1, xl: 1, lg: 1, md: 1, sm: 1, xs: 1 }}>
        <Form form={FormOrder} style={{ width: '60%' }} className="sep_forminline_label">
          <Form.Item label="内部留言" name="internalRemark">
            <Input.TextArea placeholder="请输入内部留言" showCount maxLength={500} rows={3}></Input.TextArea>
          </Form.Item>
        </Form>
      </Descriptions>
      <Descriptions title="采购明细" list={[]}>
        <div className="order_details_add_wrap">
          <div className="table_extra_flex">
            <Button
              type="primary"
              onClick={() => {
                setimportFileShow(true)
              }}
              icon={<ImportOutlined />}
              disabled={!firstClassConfigId || !productSeasonCode || !year || purchaseType === undefined}
            >
              批量导入
            </Button>
            <Button
              type="primary"
              onClick={() => {
                setisModalShow(true)
              }}
              icon={<ImportOutlined />}
              disabled={!firstClassConfigId || !productSeasonCode || !year || purchaseType === undefined}
            >
              按款式添加商品
            </Button>
            <Button
              onClick={() => {
                settableData([])
              }}
            >
              清空商品
            </Button>
          </div>
          <div className="order_details_add_searchform">
            <Form form={formOrderSearch} className="sep_forminline_label add_searchform_inline_box" layout="inline">
              <Row gutter={[10, 10]}>
                <Col {...grid}>
                  <Form.Item label="SKU商品" name="skuCode">
                    <Select
                      options={SkuOptions}
                      mode="tags"
                      maxCount={1}
                      maxTagCount="responsive"
                      placeholder="请输入SKU商品"
                    ></Select>
                  </Form.Item>
                </Col>
                <Col {...grid}>
                  <Form.Item label="下单数量" name="orderQty">
                    <InputNumber precision={0} min={0} placeholder="请输入下单数量"></InputNumber>
                  </Form.Item>
                </Col>
                <Col {...grid}>
                  <Form.Item label="采购价格" name="purchasePrice">
                    <InputNumber precision={2} min={0} placeholder="请输入采购价"></InputNumber>
                  </Form.Item>
                </Col>
                <Col {...grid}>
                  <Form.Item label="直营数量" name="directSaleQty">
                    <InputNumber precision={0} min={0} placeholder="请输入直营数量"></InputNumber>
                  </Form.Item>
                </Col>
                <Col {...grid}>
                  <Form.Item label="加盟数量" name="franchisingQty">
                    <InputNumber precision={0} min={0} placeholder="请输入加盟数量"></InputNumber>
                  </Form.Item>
                </Col>
                <Col {...grid}>
                  <Form.Item label="电商数量" name="onlineQty">
                    <InputNumber precision={0} min={0} placeholder="请输入电商数量"></InputNumber>
                  </Form.Item>
                </Col>
                <Button
                  type="primary"
                  icon={<PlusOutlined />}
                  disabled={!firstClassConfigId || !productSeasonCode || !year || purchaseType === undefined}
                  onClick={() => handleAddInfo()}
                >
                  添加
                </Button>
              </Row>
            </Form>
          </div>
          <div className="custom_table_style">
            <Table
              bordered
              columns={useDetailedColumns({ tableData, settableData })}
              dataSource={tableData}
              scroll={{ y: 400 }}
              pagination={false}
              rowKey={(rows) => rows.skuCode}
              rowHoverable={false}
              rowClassName={(_, index) => {
                return index % 2 === 0 ? '' : 'zebra-row-odd'
              }}
              summary={() => (
                <Table.Summary>
                  <Table.Summary.Row>
                    <Table.Summary.Cell index={0} align="center">
                      总计
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} colSpan={8}></Table.Summary.Cell>
                    <Table.Summary.Cell index={2} align="center">
                      {tableData?.reduce(
                        (pre, item) =>
                          mathjs.add(mathjs.bignumber(pre), mathjs.bignumber(item?.orderQty || 0)).toString(),
                        0,
                      )}
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={3} colSpan={4}></Table.Summary.Cell>
                    <Table.Summary.Cell index={4} align="center">
                      {tableData?.reduce(
                        (pre, item) =>
                          mathjs
                            .add(
                              mathjs.bignumber(pre),
                              mathjs.bignumber(
                                mathjs.multiply(
                                  mathjs.bignumber(item?.orderQty || 0),
                                  mathjs.bignumber(item?.purchasePrice || 0),
                                ) || 0,
                              ),
                            )
                            .toString(),
                        0,
                      )}
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={5}></Table.Summary.Cell>
                    <Table.Summary.Cell index={6} align="center">
                      {tableData?.reduce(
                        (pre, item) =>
                          mathjs
                            .add(
                              mathjs.bignumber(pre),
                              mathjs.bignumber(
                                mathjs.multiply(
                                  mathjs.bignumber(item?.orderQty || 0),
                                  mathjs.bignumber(item?.originSalePrice || 0),
                                ) || 0,
                              ),
                            )
                            .toString(),
                        0,
                      )}
                    </Table.Summary.Cell>
                  </Table.Summary.Row>
                </Table.Summary>
              )}
            />
          </div>
        </div>
      </Descriptions>
      <Modal
        width={2000}
        title="快捷添加商品"
        maskClosable
        open={isModalShow}
        onCancel={onModalCancel}
        footer={
          <div className="flex_end">
            <Space>
              <Button onClick={onModalCancel}>取消</Button>
              <Button loading={ispedding} type="primary" onClick={() => addTotableData()}>
                添加商品
              </Button>
            </Space>
          </div>
        }
      >
        <div className="search_header_wrap">
          <Form form={formSpuSearch} className="sep_forminline_label add_searchform_inline_box" layout="inline">
            <Row gutter={[10, 10]}>
              <Col {...grid}>
                <Form.Item label="SPU商品" name="spuCode">
                  <Input placeholder="款式编码/商品名称/助记码/工厂款号"></Input>
                </Form.Item>
              </Col>
              <Button type="primary" icon={<SearchOutlined />} onClick={() => handleAddSpu()}>
                查询
              </Button>
            </Row>
          </Form>
        </div>
        <div className="header_table_style">
          <Table
            bordered
            pagination={false}
            scroll={{
              x: 1000,
            }}
            columns={useViewSpuColumns({
              setviewList,
              viewList,
              selectedRowKeys,
            })}
            dataSource={viewList}
            rowKey={(rows) => rows.skuCode}
            rowHoverable={false}
            rowClassName={(_, index) => {
              return index % 2 === 0 ? '' : 'zebra-row-odd'
            }}
            rowSelection={{
              selectedRowKeys,
              onChange: onSelectChange,
              getCheckboxProps: (rows) => {
                return {
                  disabled: tableData.filter((item) => item.skuCode == rows.skuCode).length > 0,
                }
              },
            }}
          ></Table>
        </div>
      </Modal>
      <ImportFileModal
        loading={uploadLoading}
        open={importFileShow}
        onCancel={importFileCancel}
        onOk={importFileOk}
        form={FormUpload}
        tempCode={IMPORT_FILE_ENUM.PURCHASEW_GOODS_IMPORT}
      ></ImportFileModal>
    </DetailContainer>
  )
}
export default Index
